//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.UIDesigner.Monitor
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using System.Xml.Serialization;
    using Microsoft.Practices.Unity;
    using Microsoft.Research.ScientificWorkflow.UIDesigner.Commands;
    using Microsoft.Research.ScientificWorkflow.UIDesigner.WpfComposite;

    public class MonitorSettingService
    {
        static string xmlPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), UIDesignerCodeConstants.MONITORSETTINGSXMLPATH);

        private MonitorSettings monitorSettings;        

        public MonitorSettings Settings
        {
            get { return this.monitorSettings; }
        }

        public event EventHandler SettingsChanged;

        /// <summary>
        /// Deserialize the monitor settings file from the users local path.
        /// </summary>
        public MonitorSettings DeserializeSettings()
        {
            MonitorSettings monitorSettings = null;
            if (File.Exists(xmlPath))
            {
                try
                {
                    using (FileStream fileStream = new FileStream(xmlPath, FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(MonitorSettings));
                        object settingsObj = serializer.Deserialize(fileStream);
                        if (xmlPath != null)
                        {
                            monitorSettings = settingsObj as MonitorSettings;
                        }
                    }
                }
                catch (IOException)
                {
                    // Ignore. load defaults.
                }
                catch (UnauthorizedAccessException)
                {
                    // Ignore. load defaults.
                }
                catch (InvalidOperationException)
                {
                    // Ignore. load defaults.
                }
            }
            if (monitorSettings == null)
            {
                monitorSettings = new MonitorSettings();
            }

            this.monitorSettings = monitorSettings;
            if (this.SettingsChanged != null)
            {
                this.SettingsChanged(this, EventArgs.Empty);
            }

            return monitorSettings;
        }

        /// <summary>
        /// Serialize the monitor settings file to the users local path.
        /// </summary>
        public void SerializeSettings(MonitorSettings monitorSettings)
        {
            try
            {
                this.monitorSettings = monitorSettings;

                // Create the trident folder in user directory if it doesnt exist.
                string dirName = Path.GetDirectoryName(xmlPath);
                if (!Directory.Exists(dirName))
                {
                    MonitorSettingService.CreateDirectoryInUserFolder();
                }

                // Delete existing file.
                if (File.Exists(xmlPath))
                {
                    File.Delete(xmlPath);
                }

                if (this.SettingsChanged != null)
                {
                    this.SettingsChanged(this, EventArgs.Empty);
                }

                // Serialize to file.
                using (FileStream fileStream = new FileStream(xmlPath, FileMode.OpenOrCreate))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(MonitorSettings));
                    serializer.Serialize(fileStream, monitorSettings);
                }
            }
            catch (IOException ex)
            {
                TridentErrorHandler.HandleAndThrowBusinessLogicException(ex, 
                    TridentErrorConstants.ErrorNumber90000026, 
                    ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                TridentErrorHandler.HandleAndThrowBusinessLogicException(ex, 
                    TridentErrorConstants.ErrorNumber90000026, 
                    ex.Message);
            }
        }

        /// <summary>
        /// Create the trident directory in the user folder if it doesnt exist.
        /// </summary>
        private static void CreateDirectoryInUserFolder()
        {
            string basePath1 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                  UIDesignerCodeConstants.BASEPATH1);
            if (!Directory.Exists(basePath1))
            {
                Directory.CreateDirectory(basePath1);
            }

            string basePath2 = Path.Combine(basePath1, UIDesignerCodeConstants.BASEPATH2);

            if (!Directory.Exists(basePath2))
            {
                Directory.CreateDirectory(basePath2);
            }
        }
    }
}
